$(document).ready(function() {
    // 浮动广告控制
    const floatingAd = $('#floatingAd');
    const adBtn = $('#adBtn');

    // 广告按钮点击事件
    adBtn.on('click', function(e) {
        e.preventDefault();
        // 滚动到商品列表
        $('html, body').animate({
            scrollTop: $('.products-section').offset().top - 100
        }, 500);
    });

    // 5秒后显示广告
    setTimeout(function() {
        floatingAd.fadeIn(300);
    }, 5000);

    // 用户数据存储
    let users = [];
    try {
        const storedUsers = localStorage.getItem('users');
        users = storedUsers ? JSON.parse(storedUsers) : [];
    } catch (e) {
        console.error('Error loading users:', e);
        users = [];
    }

    let currentUser = null;
    try {
        const storedUser = localStorage.getItem('currentUser');
        currentUser = storedUser ? JSON.parse(storedUser) : null;
    } catch (e) {
        console.error('Error loading current user:', e);
        currentUser = null;
    }

    // 初始化订单数据
    let orders = [];
    try {
        const storedOrders = localStorage.getItem('orders');
        orders = storedOrders ? JSON.parse(storedOrders) : [];
    } catch (e) {
        console.error('Error loading orders:', e);
        orders = [];
    }

    // 秒杀商品数据
    const flashSaleProducts = [
        {
            id: 'fs1',
            name: 'iPhone 15 Pro Max 256GB',
            originalPrice: 9999,
            flashSalePrice: 8999,
            image: 'https://img12.360buyimg.com/n5/s720x720_jfs/t1/298575/22/12677/38252/683f0026Fc43f2902/12cbb1b1e71b267c.jpg.avif',
            description: '限时秒杀，抢完即止',
            stock: 10,
            startTime: new Date().getTime(),
            endTime: new Date().getTime() + 24 * 60 * 60 * 1000 // 24小时后结束
        },
        {
            id: 'fs2',
            name: 'MacBook Pro 14英寸 M3',
            originalPrice: 14999,
            flashSalePrice: 12999,
            image: 'https://img12.360buyimg.com/n5/s720x720_jfs/t1/300859/24/9927/33727/6836761bF39ba627b/e94b48df147242e3.png.avif',
            description: '限时秒杀，抢完即止',
            stock: 5,
            startTime: new Date().getTime(),
            endTime: new Date().getTime() + 24 * 60 * 60 * 1000
        },
        {
            id: 'fs3',
            name: 'AirPods Pro 2代',
            originalPrice: 1999,
            flashSalePrice: 1499,
            image: 'https://img14.360buyimg.com/n1/jfs/t1/312538/15/6273/96084/683e6436F7100ec08/746eb3306c589a59.jpg',
            description: '限时秒杀，抢完即止',
            stock: 20,
            startTime: new Date().getTime(),
            endTime: new Date().getTime() + 24 * 60 * 60 * 1000
        }
    ];

    // 检查登录状态
    function checkLoginStatus() {
        if (currentUser) {
            $('body').addClass('logged-in');
            updateNavLinks();
        } else {
            $('body').removeClass('logged-in');
        }
    }

    // 更新导航栏链接
    function updateNavLinks() {
        if (currentUser) {
            $('#loginBtn, #registerBtn').addClass('logged-out');
            $('#cartBtn, #ordersBtn, #profileBtn').addClass('logged-in');
        } else {
            $('#loginBtn, #registerBtn').removeClass('logged-out');
            $('#cartBtn, #ordersBtn, #profileBtn').removeClass('logged-in');
        }
    }

    // 初始化检查登录状态
    checkLoginStatus();

    // 模拟商品数据
    const products = [
        {
            id: 1,
            name: "智能手机",
            price: 2999,
            category: "electronics",
            image: "https://img20.360buyimg.com/jdcms/s480x480_jfs/t1/237597/16/23664/70962/66b07ef0F7c047c30/90690a753f15347c.jpg.avif",
            description: "最新款智能手机，性能强劲"
        },
        {
            id: 2,
            name: "休闲T恤",
            price: 99,
            category: "clothing",
            image: "https://img12.360buyimg.com/n5/s720x720_jfs/t1/255492/18/10638/19281/677e3df2F986bd90a/3dcdd0710edd50e3.jpg.avif",
            description: "舒适透气的纯棉T恤"
        },
        {
            id: 3,
            name: "编程书籍",
            price: 59,
            category: "books",
            image: "https://img11.360buyimg.com/n1/s720x720_jfs/t1/142421/36/3385/96475/5f16a0efE0d6203b1/e8e05d56217dfcb0.jpg.avif",
            description: "JavaScript高级程序设计"
        }
    ];

    // 购物车功能
    let cart = JSON.parse(localStorage.getItem('cart')) || [];

    // 添加商品到购物车
    function addToCart(productId) {
        const product = products.find(p => p.id === productId);
        if (product) {
            const existingItem = cart.find(item => item.id === product.id);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    id: product.id,
                    name: product.name,
                    price: product.price,
                    image: product.image,
                    quantity: 1
                });
            }
            saveCart();
            updateCartUI();
            alert('已添加到购物车！');
        }
    }

    // 渲染商品列表
    function renderProducts(productsToRender) {
        const $productList = $('#productList');
        $productList.empty();
        
        productsToRender.forEach(product => {
            const productCard = `
                <div class="product-card" data-product-id="${product.id}">
                    <div class="image-zoom-container">
                        <img src="${product.image}" alt="${product.name}">
                    </div>
                    <h3>${product.name}</h3>
                    <p>${product.description}</p>
                    <div class="price">￥${product.price}</div>
                    <button class="add-to-cart-btn">加入购物车</button>
                </div>
            `;
            $productList.append(productCard);
        });
    }

    // 添加商品到购物车的事件委托
    $(document).on('click', '.add-to-cart-btn', function() {
        const productId = $(this).closest('.product-card').data('product-id');
        addToCart(productId);
    });

    // 渲染秒杀商品
    function renderFlashSaleProducts() {
        const flashSaleList = $('#flashSaleList');
        flashSaleList.empty();

        flashSaleProducts.forEach(product => {
            const isEnded = new Date().getTime() > product.endTime;
            const stockPercentage = (product.stock / 20) * 100; // 假设最大库存为20

            const productElement = $(`
                <div class="flash-sale-item ${isEnded ? 'ended' : ''}">
                    <img src="${product.image}" alt="${product.name}">
                    <div class="flash-sale-info">
                        <h3>${product.name}</h3>
                        <div class="price-info">
                            <div class="original-price">原价：￥${product.originalPrice}</div>
                            <div class="flash-sale-price">秒杀价：￥${product.flashSalePrice}</div>
                        </div>
                        <div class="stock-info">库存：${product.stock}件</div>
                        <div class="flash-sale-progress">
                            <div class="progress-bar" style="width: ${stockPercentage}%"></div>
                        </div>
                        <button class="flash-sale-btn" ${isEnded || product.stock <= 0 ? 'disabled' : ''}>
                            ${isEnded ? '已结束' : product.stock <= 0 ? '已抢光' : '立即抢购'}
                        </button>
                        ${isEnded ? '<div class="flash-sale-ended">活动已结束</div>' : ''}
                    </div>
                </div>
            `);

            // 添加抢购按钮点击事件
            if (!isEnded && product.stock > 0) {
                productElement.find('.flash-sale-btn').on('click', () => handleFlashSalePurchase(product));
            }

            flashSaleList.append(productElement);
        });
    }

    // 处理秒杀购买
    function handleFlashSalePurchase(product) {
        if (!currentUser) {
            alert('请先登录');
            $('#loginModal').css('display', 'block');
            return;
        }

        if (product.stock <= 0) {
            alert('商品已抢光');
            return;
        }

        // 创建秒杀订单
        const order = {
            id: 'order_' + Date.now(),
            date: new Date().toLocaleString(),
            items: [{
                id: product.id,
                name: product.name,
                price: product.flashSalePrice,
                quantity: 1,
                image: product.image
            }],
            total: product.flashSalePrice,
            status: '待发货',
            address: currentUser.address,
            username: currentUser.username,
            type: 'flash_sale'
        };

        // 更新库存
        product.stock--;
        
        // 添加到订单列表
        orders.push(order);
        localStorage.setItem('orders', JSON.stringify(orders));
        
        // 更新UI
        renderFlashSaleProducts();
        updateOrdersUI();
        
        alert('抢购成功！');
    }

    // 更新倒计时
    function updateCountdown() {
        const now = new Date().getTime();
        const endTime = flashSaleProducts[0].endTime; // 使用第一个商品的结束时间
        const timeLeft = endTime - now;

        if (timeLeft <= 0) {
            $('#hours').text('00');
            $('#minutes').text('00');
            $('#seconds').text('00');
            return;
        }

        const hours = Math.floor(timeLeft / (1000 * 60 * 60));
        const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

        $('#hours').text(hours.toString().padStart(2, '0'));
        $('#minutes').text(minutes.toString().padStart(2, '0'));
        $('#seconds').text(seconds.toString().padStart(2, '0'));
    }

    // 初始化秒杀功能
    function initFlashSale() {
        renderFlashSaleProducts();
        updateCountdown();
        setInterval(updateCountdown, 1000);
    }

    // 初始化UI
    updateCartUI();
    updateOrdersUI();
    initFlashSale();
    renderProducts(products);

    // 搜索功能
    $('#searchBtn').click(function() {
        const searchTerm = $('#searchInput').val().toLowerCase();
        const filteredProducts = products.filter(product => 
            product.name.toLowerCase().includes(searchTerm) ||
            product.description.toLowerCase().includes(searchTerm)
        );
        renderProducts(filteredProducts);
    });

    // 分类筛选
    $('#categoryList a').click(function(e) {
        e.preventDefault();
        const category = $(this).data('category');
        const filteredProducts = category === 'all' 
            ? products 
            : products.filter(product => product.category === category);
        renderProducts(filteredProducts);
    });

    // 模态框功能
    const $loginModal = $('#loginModal');
    const $registerModal = $('#registerModal');

    // 打开登录模态框
    $('#loginBtn').click(function() {
        $loginModal.css('display', 'block');
    });

    // 打开注册模态框
    $('#registerBtn').click(function() {
        $registerModal.css('display', 'block');
    });

    // 关闭模态框
    $('.close').on('click', function() {
        $(this).closest('.modal').css('display', 'none');
    });

    // 点击模态框外部关闭
    $(window).on('click', function(e) {
        $('.modal').each(function() {
            if ($(e.target).is(this)) {
                $(this).css('display', 'none');
            }
        });
    });

    // 注册功能
    $('#registerForm').on('submit', function(e) {
        e.preventDefault();
        
        const username = $(this).find('input[name="username"]').val();
        const password = $(this).find('input[name="password"]').val();
        const confirmPassword = $(this).find('input[name="confirmPassword"]').val();
        const email = $(this).find('input[name="email"]').val();
        const address = $(this).find('input[name="address"]').val();

        // 表单验证
        if (!username || !password || !confirmPassword || !email || !address) {
            alert('请填写所有必填字段！');
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致！');
            return;
        }

        // 检查用户名是否已存在
        if (Array.isArray(users) && users.some(user => user.username === username)) {
            alert('用户名已存在！');
            return;
        }

        // 创建新用户
        const newUser = {
            username,
            password,
            email,
            address
        };

        // 确保users是数组
        if (!Array.isArray(users)) {
            users = [];
        }

        // 保存用户数据
        users.push(newUser);
        try {
            localStorage.setItem('users', JSON.stringify(users));
            alert('注册成功！');
            $('#registerModal').css('display', 'none');
            this.reset();
        } catch (e) {
            console.error('Error saving user:', e);
            alert('注册失败，请稍后重试！');
        }
    });

    // 登录功能
    $('#loginForm').submit(function(e) {
        e.preventDefault();
        const username = $(this).find('input[type="text"]').val();
        const password = $(this).find('input[type="password"]').val();

        if (!Array.isArray(users)) {
            users = [];
        }

        const user = users.find(u => u.username === username && u.password === password);
        if (user) {
            currentUser = user;
            try {
                localStorage.setItem('currentUser', JSON.stringify(user));
                checkLoginStatus();
                alert('登录成功！');
                $('#loginModal').css('display', 'none');
                this.reset();
            } catch (e) {
                console.error('Error saving login state:', e);
                alert('登录失败，请稍后重试！');
            }
        } else {
            alert('用户名或密码错误！');
        }
    });

    // 显示个人信息
    $('#profileBtn').on('click', function() {
        if (!currentUser) {
            alert('请先登录！');
            return;
        }
        $('#profileUsername').text(currentUser.username);
        $('#profileEmail').text(currentUser.email);
        $('#profileAddress').text(currentUser.address || '未设置');
        $('#profileModal').css('display', 'block');
    });

    // 打开修改信息模态框
    $('#editProfileBtn').on('click', function() {
        // 填充当前用户信息到表单
        $('#editProfileForm input[name="username"]').val(currentUser.username);
        $('#editProfileForm input[name="email"]').val(currentUser.email);
        $('#editProfileForm input[name="address"]').val(currentUser.address || '');
        
        // 显示修改信息模态框
        $('#profileModal').css('display', 'none');
        $('#editProfileModal').css('display', 'block');
    });

    // 处理修改信息表单提交
    $('#editProfileForm').on('submit', function(e) {
        e.preventDefault();
        
        const newEmail = $(this).find('input[name="email"]').val();
        const newAddress = $(this).find('input[name="address"]').val();
        
        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(newEmail)) {
            alert('请输入有效的邮箱地址！');
            return;
        }

        // 验证收货地址
        if (!newAddress.trim()) {
            alert('请输入收货地址！');
            return;
        }

        // 更新用户信息
        currentUser.email = newEmail;
        currentUser.address = newAddress;
        
        // 更新本地存储中的用户数据
        const userIndex = users.findIndex(u => u.username === currentUser.username);
        if (userIndex !== -1) {
            users[userIndex] = currentUser;
            try {
                localStorage.setItem('users', JSON.stringify(users));
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                
                // 更新显示的个人信息
                $('#profileEmail').text(newEmail);
                $('#profileAddress').text(newAddress);
                
                alert('个人信息修改成功！');
                $('#editProfileModal').css('display', 'none');
                $('#profileModal').css('display', 'block');
                this.reset();
            } catch (e) {
                console.error('Error updating profile:', e);
                alert('修改失败，请稍后重试！');
            }
        }
    });

    // 打开修改密码模态框
    $('#changePasswordBtn').on('click', function() {
        $('#profileModal').css('display', 'none');
        $('#changePasswordModal').css('display', 'block');
    });

    // 修改密码
    $('#changePasswordForm').on('submit', function(e) {
        e.preventDefault();
        const currentPassword = $(this).find('input[type="password"]').first().val();
        const newPassword = $(this).find('input[type="password"]').eq(1).val();
        const confirmNewPassword = $(this).find('input[type="password"]').last().val();

        if (currentPassword !== currentUser.password) {
            alert('当前密码错误！');
            return;
        }

        if (newPassword !== confirmNewPassword) {
            alert('两次输入的新密码不一致！');
            return;
        }

        // 更新密码
        currentUser.password = newPassword;
        const userIndex = users.findIndex(u => u.username === currentUser.username);
        if (userIndex !== -1) {
            users[userIndex] = currentUser;
            try {
                localStorage.setItem('users', JSON.stringify(users));
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                alert('密码修改成功！');
                $('#changePasswordModal').css('display', 'none');
                this.reset();
            } catch (e) {
                console.error('Error updating password:', e);
                alert('密码修改失败，请稍后重试！');
            }
        }
    });

    // 退出登录
    function logout() {
        currentUser = null;
        localStorage.removeItem('currentUser');
        checkLoginStatus();
        alert('已退出登录！');
    }

    // 添加退出登录按钮点击事件
    $('#logoutBtn').click(function(e) {
        e.preventDefault();
        logout();
    });

    // 从购物车移除商品
    function removeFromCart(productId) {
        cart = cart.filter(item => item.id !== productId);
        saveCart();
        updateCartUI();
    }

    // 更新购物车商品数量
    function updateCartItemQuantity(productId, quantity) {
        const item = cart.find(item => item.id === productId);
        if (item) {
            item.quantity = Math.max(1, parseInt(quantity));
            saveCart();
            updateCartUI();
        }
    }

    // 保存购物车到本地存储
    function saveCart() {
        localStorage.setItem('cart', JSON.stringify(cart));
    }

    // 购物车按钮点击事件
    $('#cartBtn').on('click', function() {
        if (!currentUser) {
            alert('请先登录！');
            return;
        }
        $('#cartModal').css('display', 'block');
        updateCartUI();
    });

    // 更新购物车UI
    function updateCartUI() {
        const cartItems = $('.cart-items');
        cartItems.empty();
        
        if (cart.length === 0) {
            cartItems.append('<div class="empty-cart">购物车是空的，快去选购商品吧！</div>');
            $('.cart-summary').hide();
            return;
        }
        
        $('.cart-summary').show();
        let total = 0;
        let totalItems = 0;
        
        cart.forEach(item => {
            const itemTotal = item.price * item.quantity;
            total += itemTotal;
            totalItems += item.quantity;
            
            cartItems.append(`
                <div class="cart-item">
                    <img src="${item.image}" alt="${item.name}">
                    <div class="cart-item-info">
                        <div class="cart-item-title">${item.name}</div>
                        <div class="cart-item-price">￥${item.price}</div>
                    </div>
                    <div class="cart-item-quantity">
                        <button class="quantity-btn minus" data-id="${item.id}">-</button>
                        <input type="number" class="quantity-input" value="${item.quantity}" min="1" data-id="${item.id}">
                        <button class="quantity-btn plus" data-id="${item.id}">+</button>
                    </div>
                    <div class="cart-item-subtotal">￥${itemTotal.toFixed(2)}</div>
                    <div class="remove-item" data-id="${item.id}">×</div>
                </div>
            `);
        });
        
        $('.cart-summary').html(`
            <div class="cart-summary-info">
                <div class="total-items">共 ${totalItems} 件商品</div>
                <div class="total">总计: ￥${total.toFixed(2)}</div>
            </div>
            <button class="checkout-btn" ${total === 0 ? 'disabled' : ''}>结算</button>
        `);
    }

    // 购物车数量按钮事件
    $(document).on('click', '.quantity-btn', function() {
        const id = $(this).data('id');
        const input = $(`.quantity-input[data-id="${id}"]`);
        const currentVal = parseInt(input.val());
        
        if ($(this).hasClass('plus')) {
            input.val(currentVal + 1);
        } else if ($(this).hasClass('minus')) {
            input.val(Math.max(1, currentVal - 1));
        }
        
        updateCartItemQuantity(id, input.val());
    });
    
    // 购物车数量输入框事件
    $(document).on('change', '.quantity-input', function() {
        const id = $(this).data('id');
        const newQuantity = parseInt($(this).val());
        if (newQuantity < 1) {
            $(this).val(1);
        }
        updateCartItemQuantity(id, $(this).val());
    });
    
    // 移除商品事件
    $(document).on('click', '.remove-item', function() {
        if (confirm('确定要移除这个商品吗？')) {
            const id = $(this).data('id');
            removeFromCart(id);
        }
    });

    // 结算按钮事件 - 使用事件委托
    $(document).on('click', '.checkout-btn', function() {
        if (cart.length === 0) {
            alert('购物车为空！');
            return;
        }
        
        if (!currentUser) {
            alert('请先登录！');
            return;
        }
        
        // 显示结算模态框
        $('#cartModal').css('display', 'none');
        $('#checkoutModal').css('display', 'block');
        
        // 更新结算页面信息
        $('.delivery-info').html(`
            <h3>收货信息</h3>
            <p>收货人: ${currentUser.username}</p>
            <p>收货地址: ${currentUser.address || '未设置'}</p>
        `);
        
        const orderItems = $('.order-items');
        orderItems.empty();
        
        let total = 0;
        cart.forEach(item => {
            const itemTotal = parseFloat(item.price) * parseInt(item.quantity);
            total += itemTotal;
            
            orderItems.append(`
                <div class="checkout-item">
                    <img src="${item.image}" alt="${item.name}">
                    <div class="checkout-item-info">
                        <div class="checkout-item-name">${item.name}</div>
                        <div class="checkout-item-price">￥${parseFloat(item.price).toFixed(2)} × ${item.quantity}</div>
                        <div class="checkout-item-subtotal">小计: ￥${itemTotal.toFixed(2)}</div>
                    </div>
                </div>
            `);
        });
        
        // 更新订单总金额显示
        $('#checkoutTotal').html(`
            <div class="total-label">订单总计</div>
            <div class="total-amount">总金额：￥${total.toFixed(2)}</div>
        `);

        // 更新确认按钮的点击事件
        $('.confirm-btn').off('click').on('click', function() {
            if (!currentUser) {
                alert('请先登录！');
                return;
            }
            
            if (!currentUser.address) {
                alert('请先设置收货地址！');
                $('#checkoutModal').css('display', 'none');
                $('#profileModal').css('display', 'block');
                return;
            }
            
            // 创建新订单
            const order = {
                id: Date.now().toString(),
                date: new Date().toLocaleString(),
                items: cart.map(item => ({
                    ...item,
                    price: parseFloat(item.price),
                    quantity: parseInt(item.quantity)
                })),
                total: total,
                status: '待发货',
                address: currentUser.address,
                username: currentUser.username
            };
            
            orders.push(order);
            try {
                localStorage.setItem('orders', JSON.stringify(orders));
                
                // 清空购物车
                cart = [];
                saveCart();
                updateCartUI();
                
                // 更新订单列表
                updateOrdersUI();
                
                alert('订单创建成功！');
                $('#checkoutModal').css('display', 'none');
            } catch (e) {
                console.error('Error saving order:', e);
                alert('订单创建失败，请稍后重试！');
            }
        });
    });

    // 更新订单列表UI
    function updateOrdersUI() {
        const orderList = $('.order-list');
        orderList.empty();
        
        if (!orders || orders.length === 0) {
            orderList.append('<div class="empty-orders">暂无订单记录</div>');
            return;
        }
        
        // 按时间倒序排序订单
        const sortedOrders = [...orders].sort((a, b) => {
            return new Date(b.date) - new Date(a.date);
        });
        
        sortedOrders.forEach(order => {
            if (!order || !order.items) {
                console.error('Invalid order data:', order);
                return;
            }

            const orderDate = new Date(order.date).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            orderList.append(`
                <div class="order-item">
                    <div class="order-header">
                        <div class="order-info">
                            <span class="order-number">订单号: ${order.id}</span>
                            <span class="order-date">${orderDate}</span>
                        </div>
                        <div class="order-status ${order.status === '待发货' ? 'pending' : 'shipped'}">
                            ${order.status}
                        </div>
                    </div>
                    <div class="order-products">
                        ${order.items.map(item => `
                            <div class="order-product">
                                <img src="${item.image}" alt="${item.name}">
                                <div class="order-product-info">
                                    <div class="order-product-name">${item.name}</div>
                                    <div class="order-product-price">
                                        <span class="price">￥${parseFloat(item.price).toFixed(2)}</span>
                                        <span class="quantity">× ${item.quantity}</span>
                                        <span class="subtotal">小计: ￥${(parseFloat(item.price) * parseInt(item.quantity)).toFixed(2)}</span>
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                    <div class="order-footer">
                        <div class="order-address">
                            <span class="label">收货信息：</span>
                            <span class="value">${order.username} - ${order.address || '未设置'}</span>
                        </div>
                        <div class="order-total">
                            总计: <span class="price">￥${parseFloat(order.total).toFixed(2)}</span>
                        </div>
                    </div>
                </div>
            `);
        });
    }

    // 订单按钮点击事件
    $('#ordersBtn').on('click', function() {
        if (!currentUser) {
            alert('请先登录！');
            return;
        }
        $('#ordersModal').css('display', 'block');
        updateOrdersUI();
    });

    // 主题切换功能
    const themeToggle = $('#themeToggle');
    const themeIcon = themeToggle.find('i');
    
    // 从localStorage获取主题设置
    const currentTheme = localStorage.getItem('theme') || 'light';
    if (currentTheme === 'dark') {
        $('body').addClass('dark-theme');
        themeIcon.removeClass('fa-moon').addClass('fa-sun');
    }

    // 主题切换按钮点击事件
    themeToggle.on('click', function() {
        $('body').toggleClass('dark-theme');
        if ($('body').hasClass('dark-theme')) {
            themeIcon.removeClass('fa-moon').addClass('fa-sun');
            localStorage.setItem('theme', 'dark');
        } else {
            themeIcon.removeClass('fa-sun').addClass('fa-moon');
            localStorage.setItem('theme', 'light');
        }
    });

    // 轮播图功能
    function initCarousel() {
        const slides = $('.carousel-slide');
        const indicators = $('.indicator');
        let currentSlide = 0;
        let slideInterval;

        function showSlide(index) {
            slides.removeClass('active');
            indicators.removeClass('active');
            slides.eq(index).addClass('active');
            indicators.eq(index).addClass('active');
            currentSlide = index;
        }

        function nextSlide() {
            let next = currentSlide + 1;
            if (next >= slides.length) {
                next = 0;
            }
            showSlide(next);
        }

        function prevSlide() {
            let prev = currentSlide - 1;
            if (prev < 0) {
                prev = slides.length - 1;
            }
            showSlide(prev);
        }

        // 自动播放
        function startSlideShow() {
            slideInterval = setInterval(nextSlide, 2000);
        }

        function stopSlideShow() {
            clearInterval(slideInterval);
        }

        // 事件监听
        $('.carousel-control.next').click(() => {
            stopSlideShow();
            nextSlide();
            startSlideShow();
        });

        $('.carousel-control.prev').click(() => {
            stopSlideShow();
            prevSlide();
            startSlideShow();
        });

        indicators.click(function() {
            stopSlideShow();
            showSlide($(this).index());
            startSlideShow();
        });

        // 鼠标悬停时暂停自动播放
        $('.carousel-container').hover(
            () => stopSlideShow(),
            () => startSlideShow()
        );

        // 初始化显示第一张幻灯片
        showSlide(0);
        startSlideShow();
    }

    // 在页面加载完成后初始化轮播图
    initCarousel();

    // 图片放大功能
    function initImageZoom() {
        // 创建放大镜容器和结果容器
        const zoomResult = $('<div class="image-zoom-result"><button class="image-zoom-close">&times;</button><img src="" alt=""></div>');
        $('body').append(zoomResult);

        // 为所有商品图片添加放大功能
        $('.product-card img, .flash-sale-item img').each(function() {
            const $img = $(this);
            if (!$img.parent().hasClass('image-zoom-container')) {
                const $container = $('<div class="image-zoom-container"></div>');
                $img.wrap($container);
            }
        });

        // 图片点击事件
        $(document).on('click', '.image-zoom-container', function(e) {
            e.stopPropagation(); // 阻止事件冒泡
            const $container = $(this);
            const $img = $container.find('img');
            const imgSrc = $img.attr('src');
            
            // 显示放大结果
            zoomResult.find('img').attr('src', imgSrc);
            zoomResult.fadeIn(300);
        });

        // 关闭按钮事件
        $('.image-zoom-close').click(function() {
            zoomResult.fadeOut(300);
        });

        // 点击外部关闭
        $(document).on('click', function(e) {
            if ($(e.target).closest('.image-zoom-result').length === 0 && 
                $(e.target).closest('.image-zoom-container').length === 0) {
                zoomResult.fadeOut(300);
            }
        });

        // ESC键关闭
        $(document).keydown(function(e) {
            if (e.keyCode === 27) { // ESC键
                zoomResult.fadeOut(300);
            }
        });
    }

    // 商品详情功能
    function initProductDetail() {
        const productDetailModal = document.getElementById('productDetailModal');
        const detailMainImage = document.getElementById('detailMainImage');
        const thumbnailList = document.getElementById('thumbnailList');
        const detailProductName = document.getElementById('detailProductName');
        const detailPrice = document.getElementById('detailPrice');
        const detailOriginalPrice = document.getElementById('detailOriginalPrice');
        const detailDescription = document.getElementById('detailDescription');
        const detailStock = document.getElementById('detailStock');
        const detailQuantity = document.getElementById('detailQuantity');
        const minusBtn = document.querySelector('.quantity-btn.minus');
        const plusBtn = document.querySelector('.quantity-btn.plus');
        const addToCartBtn = document.getElementById('detailAddToCart');
        const buyNowBtn = document.getElementById('detailBuyNow');

        // 显示商品详情
        function showProductDetail(product) {
            detailProductName.textContent = product.name;
            detailPrice.textContent = `￥${product.price}`;
            detailOriginalPrice.textContent = `￥${product.originalPrice || product.price * 1.2}`;
            detailDescription.textContent = product.description;
            detailStock.textContent = product.stock > 0 ? `有货 (${product.stock}件)` : '暂时缺货';
            detailMainImage.src = product.image;
            detailQuantity.value = 1;

            // 清空并重新加载缩略图
            thumbnailList.innerHTML = '';
            const images = [product.image, ...(product.images || [])];
            images.forEach((image, index) => {
                const thumbnail = document.createElement('div');
                thumbnail.className = `thumbnail-item ${index === 0 ? 'active' : ''}`;
                thumbnail.innerHTML = `<img src="${image}" alt="缩略图${index + 1}">`;
                thumbnail.addEventListener('click', () => {
                    detailMainImage.src = image;
                    document.querySelectorAll('.thumbnail-item').forEach(item => item.classList.remove('active'));
                    thumbnail.classList.add('active');
                });
                thumbnailList.appendChild(thumbnail);
            });

            productDetailModal.style.display = 'block';
        }

        // 数量选择器功能
        minusBtn.addEventListener('click', () => {
            const currentValue = parseInt(detailQuantity.value);
            if (currentValue > 1) {
                detailQuantity.value = currentValue - 1;
            }
        });

        plusBtn.addEventListener('click', () => {
            const currentValue = parseInt(detailQuantity.value);
            const maxStock = 100; // 假设最大库存为100
            if (currentValue < maxStock) {
                detailQuantity.value = currentValue + 1;
            }
        });

        // 加入购物车
        addToCartBtn.addEventListener('click', () => {
            const quantity = parseInt(detailQuantity.value);
            const productId = parseInt(productDetailModal.dataset.productId);
            addToCart(productId);
            productDetailModal.style.display = 'none';
        });

        // 立即购买
        buyNowBtn.addEventListener('click', () => {
            const quantity = parseInt(detailQuantity.value);
            const productId = parseInt(productDetailModal.dataset.productId);
            addToCart(productId);
            productDetailModal.style.display = 'none';
            $('#cartModal').css('display', 'block');
        });

        // 关闭模态框
        const closeBtn = productDetailModal.querySelector('.close');
        closeBtn.addEventListener('click', () => {
            productDetailModal.style.display = 'none';
        });

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === productDetailModal) {
                productDetailModal.style.display = 'none';
            }
        });

        // 为商品卡片添加点击事件
        $(document).on('click', '.product-card', function(e) {
            // 如果点击的是图片容器或加入购物车按钮，则不触发商品详情
            if ($(e.target).closest('.image-zoom-container').length > 0 || 
                $(e.target).hasClass('add-to-cart-btn')) {
                return;
            }
            
            const productId = $(this).data('product-id');
            const product = products.find(p => p.id === productId);
            if (product) {
                productDetailModal.dataset.productId = productId;
                showProductDetail(product);
            }
        });
    }

    // 在页面加载完成后初始化功能
    initImageZoom();
    initProductDetail();

    // 在线客服功能
    initChat();

    // 初始化滚动文字公告栏
    initAnnouncement();
});

// 在线客服功能
function initChat() {
    const chatButton = document.getElementById('chatButton');
    const chatModal = document.getElementById('chatModal');
    const closeButton = chatModal.querySelector('.close');
    const chatMessages = document.getElementById('chatMessages');
    const chatInput = document.getElementById('chatInput');
    const sendButton = document.getElementById('sendButton');

    // 预设的客服回复
    const customerServiceResponses = {
        '价格': '您好，我们的商品价格都是明码标价的，您可以在商品详情页查看具体价格。',
        '优惠': '目前正在进行限时特惠活动，新用户首单立减50元！',
        '发货': '我们会在24小时内发货，一般3-5天可以收到商品。',
        '退货': '支持7天无理由退换货，商品需保持原包装和标签完整。',
        '支付': '我们支持支付宝、微信支付等多种支付方式。',
        '会员': '注册成为会员可以享受更多优惠和专属服务。',
        '发票': '可以开具电子发票，请在订单备注中说明。',
        '售后': '我们的售后服务热线是400-123-4567，工作时间为9:00-18:00。',
        '咨询': '您好，请问有什么可以帮您？',
        '帮助': '您可以通过以下方式获取帮助：\n1. 查看帮助中心\n2. 联系在线客服\n3. 拨打客服热线',
        '物流': '您可以在订单详情页查看物流信息，我们使用顺丰、中通等快递公司配送。',
        '退款': '退款申请通过后，款项将在1-3个工作日内原路退回。'
    };

    // 快捷回复选项
    const quickReplies = [
        '价格咨询',
        '优惠活动',
        '发货时间',
        '退换货',
        '支付方式',
        '会员服务',
        '物流查询',
        '退款问题'
    ];

    // 打开聊天窗口
    chatButton.addEventListener('click', () => {
        chatModal.style.display = 'block';
        // 添加欢迎消息
        if (chatMessages.children.length === 0) {
            addMessage('客服', '您好！欢迎使用在线客服，请问有什么可以帮您？', 'received');
            // 添加快捷回复选项
            addQuickReplies();
        }
        // 自动滚动到底部
        chatMessages.scrollTop = chatMessages.scrollHeight;
    });

    // 关闭聊天窗口
    closeButton.addEventListener('click', () => {
        chatModal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
        if (e.target === chatModal) {
            chatModal.style.display = 'none';
        }
    });

    // 发送消息
    function sendMessage() {
        const message = chatInput.value.trim();
        if (message) {
            addMessage('我', message, 'sent');
            chatInput.value = '';
            
            // 模拟客服回复
            setTimeout(() => {
                let response = '抱歉，我暂时无法理解您的问题。请稍等，正在为您转接人工客服...';
                
                // 根据关键词匹配回复
                for (let keyword in customerServiceResponses) {
                    if (message.includes(keyword)) {
                        response = customerServiceResponses[keyword];
                        break;
                    }
                }
                
                addMessage('客服', response, 'received');
            }, 1000);
        }
    }

    // 添加消息到聊天窗口
    function addMessage(sender, text, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `chat-message ${type}`;
        messageDiv.innerHTML = `
            <div class="message-content">
                <span class="sender">${sender}</span>
                <p>${text}</p>
            </div>
        `;
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    // 添加快捷回复选项
    function addQuickReplies() {
        const quickRepliesDiv = document.createElement('div');
        quickRepliesDiv.className = 'quick-replies';
        quickRepliesDiv.innerHTML = `
            <div class="quick-reply-title">常见问题：</div>
            <div class="quick-reply-buttons">
                ${quickReplies.map(text => `<button class="quick-reply-btn">${text}</button>`).join('')}
            </div>
        `;
        chatMessages.appendChild(quickRepliesDiv);

        // 添加快捷回复按钮点击事件
        const quickReplyButtons = quickRepliesDiv.querySelectorAll('.quick-reply-btn');
        quickReplyButtons.forEach(button => {
            button.addEventListener('click', () => {
                const question = button.textContent;
                addMessage('我', question, 'sent');
                setTimeout(() => {
                    const response = customerServiceResponses[question] || '正在为您查询相关信息...';
                    addMessage('客服', response, 'received');
                }, 1000);
            });
        });
    }

    // 发送按钮点击事件
    sendButton.addEventListener('click', sendMessage);

    // 输入框回车发送
    chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 输入框获得焦点时自动滚动到底部
    chatInput.addEventListener('focus', () => {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    });

    // 添加输入框动画效果
    chatInput.addEventListener('focus', () => {
        chatInput.style.transform = 'scale(1.02)';
    });

    chatInput.addEventListener('blur', () => {
        chatInput.style.transform = 'scale(1)';
    });
}

// 个人信息页面
function showProfile() {
    // 这里可以添加显示个人信息的逻辑
    alert('个人信息页面开发中...');
}

// 订单页面
function showOrders() {
    // 这里可以添加显示订单的逻辑
    alert('订单页面开发中...');
}

// 初始化所有功能
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    initProductDetail();
    initCart();
    initChat();
});

// 初始化滚动文字公告栏
function initAnnouncement() {
    const announcements = [
        '欢迎来到我们的商城！',
        '新用户首单立减50元！',
        '全场商品满300减30！',
        '限时特惠，抢购从速！',
        '支持7天无理由退换货！'
    ];

    const announcementContent = document.querySelector('.announcement-content');
    if (announcementContent) {
        // 创建重复的公告内容以实现无缝滚动
        const content = announcements.map(text => `<span>${text}</span>`).join('');
        announcementContent.innerHTML = content + content;
    }
} 